/**
 * created by zhouli on 2018/12/20
 * 角色（职能）菜单管理
 * todo
 * 名称做多语言
 */
import React from 'react';
import {connect} from 'react-redux';
import {Menu, Icon, Modal,Popover, Button, Form, Input, Select, Switch, Spin} from 'antd';
import 'styles/permission-setting/components/role-menu.scss';
import RSService from 'containers/permission-setting/components/role-menu.service';
import {deepCopy, messages, trim, getSubText} from "share/common";
import {
  roleModel as originRoleModel,
} from 'containers/permission-setting/permission-setting.model';
import debounce from 'lodash.debounce';
const roleModel = deepCopy(originRoleModel);
const Option = Select.Option;
const SubMenu = Menu.SubMenu;
const Search = Input.Search;
const FormItem = Form.Item;
import {permissionTypeList,} from 'containers/permission-setting/permission-setting.model';

class RoleMenu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      role: deepCopy(roleModel),
      modalKey: 0,
      loading: false,
      originRoleList: [],
      roleList: [],//职能列表
      visible: false,
      openKeys: [],//默认展开的类型
      selectedKeys: [],//默认展开的菜单
      permissionCategoryList: permissionTypeList,//只能类型
    };
    this.fiterRoleListInner = debounce(this.fiterRoleListInner, 500);
  }

  componentDidMount() {
    this.getRoleList();
  }

  //点击具体菜单
  handleClick = ({item, key}) => {
    let selectedKeys = [key];
    let data = item.props.data;
    this.setState({
      selectedKeys
    }, () => {
      this.props.onSelect && this.props.onSelect(selectedKeys, data)
    })
  };
  //点击菜单折叠
  openMenuChange = (openKeys) => {
    this.setState({
      openKeys
    })
  };
  //获取角色列表
  getRoleList = (activeRole) => {
    this.setState({
      loading: true
    });
    RSService.getRoleList()
      .then(res => {
        let [selectedKeys, openKeys, data] = RSService.getSelectedKeys(deepCopy(res.data), activeRole);
        if (this.props.roleCache) {
          let roleList = deepCopy(res.data);
          //roleList 一旦启用了新权限，roleList 后端至少会初始化一个角色
          roleList = roleList.map(item => {
            if (item.id === this.props.roleCache.id) {
              item = this.props.roleCache;
            }
            return item;
          });
          this.setState({
            visible: false,
            loading: false,
            originRoleList: deepCopy(roleList),//用来过滤
            roleList: roleList
          }, () => {
            this.delNewRole(this.props.roleCache, true);
          })
        } else {
          this.setState({
            openKeys,
            selectedKeys,
            visible: false,
            loading: false,
            originRoleList: deepCopy(res.data),//用来过滤
            roleList: res.data
          }, () => {
            this.props.onSelect && this.props.onSelect(selectedKeys, data)
          })
        }
      })
  };

  fiterRoleListInner=( val )=>{
    let filterList = [];
    let originRoleList = deepCopy(this.state.originRoleList);
    let openKeys = this.state.openKeys;
    let selectedKeys = this.state.selectedKeys;
    let data = null;
    originRoleList.map(item => {
      if (selectedKeys[0] === item.id) {
        //手动点击激活职能之前，保持原来激活的职能
        data = item;
      }
      if (item.permissionName.match(val)) {
        filterList.push(item);
      }
    });
    if (val && val.length > 0) {
      //搜索时全部打开
      openKeys = ['ADMIN', 'FINANCE', 'OTHER'];
    } else {
      [selectedKeys, openKeys, data] = RSService.getSelectedKeys(deepCopy(originRoleList));
    }
    this.setState({
      openKeys,
      selectedKeys,
      roleList: filterList
    }, () => {
      this.props.onSelect && this.props.onSelect(selectedKeys, data)
    })
  }
  fiterRoleList = (e) => {
    let val = trim(e.target.value);
    this.fiterRoleListInner(getSubText(val, 100));
  };
  //展示模态框
  showModalRole = (_role, isUpdate) => {
    this.props.form.resetFields();
    let modalKey = this.state.modalKey;
    modalKey++;
    let role = {};
    if (isUpdate) {
      role = _role;
    } else {
      role = deepCopy(roleModel);
    }
    this.setState({
      modalKey,
      role,
      visible: true,
    });
  };
  //取消
  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };
  //保存角色
  handleSaveRole = (e) => {
    //如果没有这个，页面会刷新
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, _values) => {
      if (!err) {
        const {role} = this.state;
        let values = deepCopy(_values);
        if (role.id) {
          values.id = role.id;
          values.tenantId = role.tenantId;
          this.updateRole(values)
        } else {
          this.createRole(values)
        }
      }
    })
  };
  //新增
  createRole = (role) => {
    this.setState({
      loading: true
    });
    RSService.createRole(role)
      .then(res => {
        let newRole = res.data;
        this.delNewRole(newRole);
      })
      .catch(() => {
        this.setState({
          loading: false
        })
      })
  };
  //编辑
  updateRole = (role) => {
    this.setState({
      loading: true
    });
    RSService.updateRole(role)
      .then(res => {
        let newRole = res.data;
        //编辑之后，状态改变，可能导致排序改变，这边重新获取列表，但是激活的职能不变
        this.getRoleList(newRole);
      })
      .catch(() => {
        this.setState({
          loading: false
        })
      })
  };
  //新增或者更新，对视图的刷新
  delNewRole = (newRole, isUpdate) => {
    let roleList = deepCopy(this.state.originRoleList);
    if (!isUpdate) {
      roleList.push(newRole);
    }
    let [selectedKeys, openKeys, data] = RSService.getSelectedKeys(deepCopy(roleList), newRole);
    this.setState({
      openKeys,
      selectedKeys,
      loading: false,
      originRoleList: deepCopy(roleList),
      visible: false,
      roleList
    }, () => {
      this.props.onSelect && this.props.onSelect(selectedKeys, data);
    })
  };
  //编辑form表单改变
  handleRoleChange = () => {
    this.setState({
      loading: false
    })
  };
  //渲染角色列表
  renderRoleList = (list, type) => {
    let menuLoading = this.props.menuLoading;
    if (list.length > 0) {
      const {selectedKeys} = this.state;
      return list.map((item) => {
        if (item.permissionCategory === type) {
          let name = 'name f-left';
          if (!item.enabled) {
            name = 'name f-left disabled-name';
          }
          return <Menu.Item key={item.id}
                            disabled={menuLoading}
                            data={item}>
            <div className="name-wrap">
              <div className={name}>
                <Popover content={item.permissionName}
                         overlayStyle={{maxWidth: 400}}>
                  {item.permissionName}
                </Popover>
              </div>
              {this.props.isShowEdit &&
              selectedKeys.length > 0 && selectedKeys[0] === item.id &&
              <div className='edit-btn f-right'
                   onClick={() => {
                     this.showModalRole(item, true)
                   }}>{messages('common.edit')/*编辑*/}</div>}
            </div>
          </Menu.Item>
        }
      })
    } else {
      return <div/>
    }
  };
  //渲染子菜单
  renderSubMenu = (permissionCategoryList) => {
    return permissionCategoryList.map(item => {
      return <SubMenu key={item.value}
                      title={
                        <div className="role-menu-title">
                          <img className="icon" src={item.iconType}/>
                          <span>{item.name}</span>
                        </div>
                      }>
        {this.renderRoleList(this.state.roleList, item.value)}
      </SubMenu>
    })
  };
  //渲染职能类别
  renderSelectOption = (permissionCategoryList) => {
    return permissionCategoryList.map(item => {
      return <Option value={item.value}>{item.name}</Option>
    })
  };

  render() {
    const {role, visible, loading, openKeys, selectedKeys, permissionCategoryList} = this.state;
    const {getFieldDecorator} = this.props.form;
    return (
      <div className="role-menu-wrap">
        <div className='inner-role-menu-wrap'>
          <div className='title'>
            <div className='text f-left'>{messages('permission-setting.key1')/*职能列表*/}</div>
            {this.props.isShowEdit && <div className='new-btn f-right'>
              <Button onClick={this.showModalRole}>{messages('permission-setting.key2')/*新增职能*/}</Button>
            </div>}
            <div className='clear'/>
          </div>
          <div className='s-inp'>
            <Search
              placeholder={messages('permission-setting.key3')/*输入职能名称*/}
              onChange={this.fiterRoleList}
            />
          </div>
          <div className='s-tree'>
            <Spin spinning={this.props.menuLoading}>
              <Menu
                onClick={this.handleClick}
                onOpenChange={this.openMenuChange}
                mode="inline"
                selectedKeys={selectedKeys}
                openKeys={openKeys}
                style={{width: 256}}
              >
                {this.renderSubMenu(permissionCategoryList)}
              </Menu>
            </Spin>
          </div>
        </div>
        <div className="new-hotfix-model"/>
        <Modal
          getContainer={() => {
            return document.getElementsByClassName("new-hotfix-model")[0];
          }}
          maskClosable={false}
          closable
          width={600}
          title={role.id ? messages('permission-setting.key4')/*编辑职能*/ : messages('permission-setting.key2')/*新增职能*/}
          visible={visible}
          destroyOnClose={true}
          footer={null}
          onCancel={this.handleCancel}
        >
          <div className="role-modal-inner-wrap">
            <Form onChange={this.handleRoleChange}>
              <FormItem
                label={messages('permission-setting.key5')/*职能类别*/}
                colon={true}>
                {getFieldDecorator('permissionCategory', {
                  initialValue: role.permissionCategory,
                  rules: [
                    {
                      required: true,
                      message: messages("common.please.select")
                    },
                  ]
                })(
                  <Select
                    disabled={role.id}
                    placeholder={messages("common.please.select")}
                    onChange={this.handleChange}
                  >
                    {this.renderSelectOption(permissionCategoryList)}
                  </Select>
                )
                }
              </FormItem>
              <FormItem
                label={messages('permission-setting.key6')/*职能代码*/}
                colon={true}>
                {getFieldDecorator('permissionCode', {
                  initialValue: role.permissionCode,
                  rules: [
                    {
                      required: true,
                      message: messages("common.please.enter")
                    },
                  ]
                })(
                  <Input
                    disabled={role.id}
                    placeholder={messages("common.please.enter")}/>)
                }
              </FormItem>
              <FormItem
                label={messages('permission-setting.key7')/*职能名称*/}
                colon={true}>
                {getFieldDecorator('permissionName', {
                  initialValue: role.permissionName,
                  rules: [
                    {
                      required: true,
                      message: messages("common.please.enter")
                    },
                  ]
                })(
                  <Input placeholder={messages("common.please.enter")}/>)
                }
              </FormItem>

              <FormItem
                label={messages('common.column.status')/*状态*/}
                colon={true}>
                {getFieldDecorator("enabled", {
                  initialValue: role.enabled,
                  valuePropName: 'checked',
                })
                (<Switch checkedChildren={<Icon type="check"/>}
                         unCheckedChildren={<Icon type="cross"/>}/>)
                }
              </FormItem>

              <div className="role-manage-from-footer">
                <Button onClick={this.handleCancel}>
                  {messages("common.cancel")}
                </Button>
                &nbsp;&nbsp;
                <Button type="primary"
                        onClick={this.handleSaveRole}
                        loading={loading}>
                  {messages("common.save")}
                </Button>
              </div>
            </Form>
          </div>
        </Modal>
      </div>
    )
  }
}

RoleMenu.propTypes = {
  roleCache: React.PropTypes.any,//
  menuLoading: React.PropTypes.bool,//是否正在加载资源
  isShowEdit: React.PropTypes.bool,//是否显示编辑按钮
  onSelect: React.PropTypes.func,// 点击激活某一个角色
};

RoleMenu.defaultProps = {
  roleCache: null,
  menuLoading: false,
  isShowEdit: true
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization,
    company: state.login.company,
    language: state.main.language,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(Form.create()(RoleMenu));
